<template>
  <div class="check-box-container">
    <el-row
      :gutter="22"
      class="row-choose-box"
      v-for="(item, index) in optionList"
      :key="index">
      <el-col :span="3">
        <el-checkbox v-model="code" :label="item.code">
          {{ item.code }}：
        </el-checkbox>
      </el-col>
      <el-col :span="15">
        <el-input v-model="item.title"></el-input>
      </el-col>
      <el-col :span="6">
        <el-upload
          class="avatar-uploader"
          action="/"
          :show-file-list="false"
          :on-change="res=>imgPreview(res, item)">
          <img v-if="item.img" :src="item.img" class="avatar">
          <i v-else class="avatar-uploader-icon">点击上传</i>
        </el-upload>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  name: 'CheckBox',
  props: {
    options: {
      required: true
    }
  },
  data: function() {
    return {
      code: []
    }
  },
  created () {
    // 初始化选中项
    const arr = this.optionList.filter(item => {
      return item.isRight === 1
    })
    this.code = arr.map(x => x.code)
  },
  methods: {
    // 照片上传
    imgPreview: function(file, item) {
      const fileName = file.name;
      const regex = /(.jpg|.jpeg|.gif|.png|.bmp)$/;
      if (regex.test(fileName.toLowerCase())) {
        item.img = URL.createObjectURL(file.raw) // 获取URL
      } else {
        this.$message.error('请选择图片文件');
      }
    },
    onChange() {
      if (!this.options) {
        this.$emit('changed', this.optionList)
      }
    }
  },
  watch: {
    code () {
      // 多选。验证选中项的isRight
      this.optionList.forEach(item => {
        item.isRight = this.code.indexOf(item.code) > -1
      }, this)
    },
    optionList: {
      handler () {
        this.onChange()
      },
      deep: true
    }
  },
  computed: {
    optionList () {
      return Array.isArray(this.options) && this.options ? this.options : [
        {
          code: 'A',
          title: '',
          img: '',
          isRight: true
        },
        {
          code: 'B',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'C',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'D',
          title: '',
          img: '',
          isRight: false
        }
      ]
    }
  }
};
</script>

<style lang="less" scoped>
.check-box-container {
  width: 50%;
}
.row-choose-box {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}
</style>
